﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Way.Bus.Controllers;
using Way.Bus.WMS.Model;
using Way.EAP.DataAccess.Data;
using System.Data;
using Way.EAP.DataAccess.Entity;
using Way.Contract.Data;
using Way.Contract.Data.ControllerData;
using Way.Contract.MVC;
using Way.Bus.Model;
using Way.Bus.WMS.Controllers;
using System.Configuration;
using Way.Bus.WMS.SF.Model;
using InterfaceService.DataAccess;

namespace Way.Bus.WMS.SF.Controllers
{
    public class SFStockInfoMaterialsController : StockInfoMaterialsController
    {

        #region 初始化数据方法
        protected override void OnInitViewChildItem(Way.Contract.Data.ModelData data, Way.Contract.Data.ItemData item)
        {
            if (data.name.EndsWith("StockInfoMaterials"))
            {
                switch (item.field.ToLower())
                {
                    case "code":
                        item.visible = true;
                        item.index = 1;
                        break;
                    case "mcode":
                        item.visible = true;
                        item.index = 2;
                        break;
                    case "fmodel":
                        item.visible = true;
                        item.index = 3;
                        break;
                    case "depotwbs":
                        item.visible = true;
                        item.index = 4;
                        break;
                    case "lastintime":
                        item.visible = true;
                        item.index = 5;
                        break;
                    case "portcode":
                        item.visible = true;
                        item.index = 6;
                        break;
                    case "num":
                        item.visible = true;
                        item.index = 7;
                        break;
                    case "remark":
                        item.visible = true;
                        item.index = 8;
                        break;
                    default:
                        item.visible = false;
                        break;
                }
            }
            if (data.name.EndsWith("InfoInSequence"))
            {
                data.visible = false;
            }
        }

        #endregion

        protected override ActionCommand[] OnInitCommand(ActionCommand[] commands)
        {
            //获取所有按钮集合
            foreach (ActionCommand ac in commands)
            {
                if (ac.command == "add")
                {
                    ac.visible = false;
                }
                if (ac.command == "edit")
                {
                    ac.name = "冻结";
                    ac.visible = false;
                }
                if (ac.command == "remove")
                {
                    ac.visible = false;
                }
                if (ac.command == "SubmitData")
                {
                    ac.visible = false;
                }
                if (ac.command == "OnSubmitData")
                {
                    ac.visible = false;
                }
                if (ac.command == "ReviewedData")
                {
                    ac.visible = false;
                }
                if (ac.command == "ImportExcel")
                {
                    ac.visible = false;
                }
            }
            return commands;
        }


        /// <summary>
        /// 所选择的申请ID  
        /// Ports托盘表  WareHouse货位表  StockInfo_Materials库存表
        /// </summary>
        [WhereParameter]
        public string ytpm { get; set; }//原托盘吗
        public string yhw { get; set; } //原货位
        public double num { get; set; } //件数
        public string mtpm { get; set; }//目托盘吗
        public string mhw { get; set; } //目货位
        protected override void OnEditing(Contract.MVC.ControllerBase.SaveEvent item)
        {
            //ytpm = 11;
            //yhw = 1;
            //num = 1;
            if (ytpm == null)
            {
                StockInfoMaterials info = item.Item as StockInfoMaterials;
                DataTable dt = this.model.GetDataAction().GetDataTable("select * from Acc_WMS_InfoMaterials where DEPOTWBS=" + info.DEPOTWBS);
                if (dt.Rows.Count > 0 && info.DEPOTWBS != "7066" && info.DEPOTWBS != "7067" && info.DEPOTWBS != "7068" && info.DEPOTWBS != "7069")
                    throw new Exception("该货位已经存在一个托盘，请重新扫描货位！");
                base.OnEditing(item);
                if (info.FREEZENUM >= 0 && info.FREEZENUM <= Convert.ToDouble(info.NUM))
                {
                    //info.NUM -= info.FREEZENUM;
                    //info.ISLOCK = true;
                }
                else
                {
                    throw new Exception("请输入正确的冻结数量");
                }

            }
            else//判断执行的是终端程序，否侧就是后台网站
            {
                DateTime strYdatatime = DateTime.Now;//原货位入库时间
                string[] sArray = ytpm.Split(',');
                ytpm = sArray[0];
                yhw = sArray[1];
                mtpm = sArray[2];
                mhw = sArray[3];
                num = double.Parse(sArray[4]);
                //if(yhw=="'完工收货区货位'")
                //    throw new Exception("该托盘没有上架，不能移位！");

                WareHouse wh = null;
                Ports so = null;
                StockInfoMaterials sm = null; //目标托盘仓库
                StockInfoMaterials sm1 = null;//目标货位仓库
                //移动做的工作1原托盘状态 ，目标托盘状态
                //           2货位ADDRESS  
                //           3库存  存储位置、托盘编码,库存数量

                //原的数据
                EntityList<Ports> listtp = new EntityList<Ports>(this.model.GetDataAction());
                listtp.GetData("PORTNO=" + ytpm);
                Ports psy = listtp[0];
                EntityList<StockInfoMaterials> listkcy = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
                listkcy.GetData("PORTCODE=" + psy.ID);
                StockInfoMaterials smy = listkcy[0];
                strYdatatime = smy.LASTINTIME;
                EntityList<WareHouse> listtpy = new EntityList<WareHouse>(this.model.GetDataAction());
                // listtpy.GetData();
                // listtpy.GetData("ID=" + sm.DEPOTWBS);
                listtpy.GetData("WAREHOUSENAME=" + yhw);
                WareHouse hwy = listtpy[0];
                //目标的数据
                EntityList<Ports> listtpm = new EntityList<Ports>(this.model.GetDataAction());
                listtpm.GetData("PORTNO=" + mtpm);
                if (listtpm.Count > 0)
                    so = listtpm[0];
                else
                    throw new Exception("目标托盘不存在,不可以移动");
                EntityList<WareHouse> listtwh = new EntityList<WareHouse>(this.model.GetDataAction());
                listtwh.GetData("WAREHOUSENAME=" + mhw);
                if (listtwh.Count > 0)
                    wh = listtwh[0];
                else
                    throw new Exception("货位不存在,不可以移动");
                EntityList<StockInfoMaterials> listsi = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
                listsi.GetData("PORTCODE=" + so.ID);
                if (listsi.Count > 0)
                    sm = listsi[0];
                else
                {
                    sm = new StockInfoMaterials();
                    sm.Code = smy.Code;
                    sm.DEPOTWBS = wh.ID.ToString();
                    sm.PORTCODE = so.ID.ToString();
                    listsi.Add(sm);
                }
                EntityList<StockInfoMaterials> listsih = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
                listsih.GetData("DEPOTWBS=" + wh.ID);
                if (listsih.Count > 0)
                    sm1 = listsi[0];//item.Item as StockInfo_Materials;  //库存
                else
                {
                    listsih.GetData("PORTCODE=" + so.ID);
                    if (listsih.Count > 0)
                        sm1 = listsi[0];//item.Item as StockInfo_Materials;  //库存
                }
                if (wh == null)//货位不存在
                {
                    //提示
                    throw new Exception("货位不存在,不可以移动");
                }
                else
                { //货位存在
                    if (wh.STATUS.Equals("0")) //货位未占用
                    {
                        //托盘
                        if (so == null)//托盘不存在
                        {
                            throw new Exception("托盘不存在,不可以移动");
                        }
                        else
                        {//托盘存在
                            //分情况
                            zhixing(psy, so, smy, sm, hwy, wh);
                        }
                    }
                    else
                    { //货位占用
                        if (so == null)//托盘不存在
                        {
                            throw new Exception("托盘不存在,不可以移动");
                        }
                        else
                        {
                            if (sm1 == null)//目标货位商品
                            {
                                zhixing(psy, so, smy, sm, hwy, wh);
                            }
                            else
                            {
                                //throw new Exception("货位占用,不可以移动");
                                if (sm1.Code == sm.Code)
                                { //目标托盘和目标货位托盘的库存id相同，可以移动
                                    zhixing(psy, so, smy, sm, hwy, wh);
                                }
                                else
                                { //不可以移动
                                    throw new Exception("货位占用,不可以移动");
                                }
                            }
                        }
                    }
                }
                if (smy.NUM == 0)
                    listkcy.Remove(smy);
                listsi[0].LASTINTIME = strYdatatime;
                listtpm.Save();//目标托盘
                listsi.Save();//目标库存
                listtwh.Save();//目标货位
                listtp.Save();//原托盘
                listkcy.Save();//原库存
                listtpy.Save();//原货位
                ytpm = null;
            }
            string strSql = " delete Acc_WMS_InfoMaterials where NUM=0 ; update Acc_WMS_Ports set STATUS=0 ; update Acc_WMS_Ports set STATUS=1 where ID in (select PORTCODE from Acc_WMS_InfoMaterials )";
            this.model.GetDataAction().Execute(strSql);
        }

        public void zhixing(Ports psy, Ports so, StockInfoMaterials smy, StockInfoMaterials sm, WareHouse hwy, WareHouse wh)
        {
            if (so.PORTNO.Equals(ytpm))//托盘吗相同,直接移动，但需要判断是否是全部移走
            {
                if (smy.NUM == num)
                { //全部移走,改变原货位的状态闲置，目表货位可用，原货位位置=目标或为位置
                    DataTable dt = this.model.GetDataAction().GetDataTable("select * from Acc_WMS_InfoMaterials where DEPOTWBS=" + wh.ID);
                    if (dt.Rows.Count > 0)
                        throw new Exception("该货位已经存在一个托盘，请重新扫描货位！");
                    hwy.STATUS = "0";
                    wh.STATUS = "1";
                    smy.DEPOTWBS = wh.ID.ToString();
                }
                else if (num > smy.NUM)
                {
                    throw new Exception("仓库中的货物少于" + num);
                }
                else
                { //非全部移走,原货位位置=目标或为位置
                    wh.STATUS = "1";
                    smy.DEPOTWBS = wh.ID.ToString();
                }
            }
            else
            { //托盘吗不同
                if (so.STATUS.Equals("0"))//托盘可用
                {
                    //判断目标货位是否可用
                    DataTable dt = this.model.GetDataAction().GetDataTable("select * from Acc_WMS_InfoMaterials where DEPOTWBS=" + wh.ID);
                    if (dt.Rows.Count > 0)
                        throw new Exception("该货位已经存在一个托盘，请重新扫描货位！");
                    if (smy.Code == sm.Code)
                    { //原托盘和目托盘的库存id相同，可以移动
                        if (smy.NUM == num)
                        { //全部移动
                            hwy.STATUS = "0";
                            wh.STATUS = "1";
                            so.STATUS = "1";
                            psy.STATUS = "0";
                            //smy.DEPOTWBS = wh.ID.ToString();
                            sm.NUM = smy.NUM + sm.NUM;
                            smy.NUM = 0;
                        }
                        else if (num > smy.NUM)
                        {
                            throw new Exception("仓库中的货物少于" + num);
                        }
                        else
                        { //非全部移动
                            wh.STATUS = "1";
                            so.STATUS = "1";
                            //hwy.ADDRESS = wh.ADDRESS;
                            smy.NUM = smy.NUM - num;
                            sm.NUM = sm.NUM + num;
                            //smy.DEPOTWBS = wh.ID.ToString();
                        }
                    }
                    else
                    { //不可以移动
                        throw new Exception("不是同一种货物,不可以移动");
                    }
                }
                else
                { //托盘不可用
                    if (smy.Code == sm.Code)
                    { //原托盘和目托盘的库存id相同，可以移动
                        if (smy.NUM == num)
                        { //全部移动
                            hwy.STATUS = "0";
                            wh.STATUS = "1";
                            so.STATUS = "1";
                            psy.STATUS = "0";
                            //smy.DEPOTWBS = wh.ID.ToString();
                            sm.NUM = smy.NUM + sm.NUM;
                            smy.NUM = 0;
                        }
                        else if (num > smy.NUM)
                        {
                            throw new Exception("仓库中的货物少于" + num);
                        }
                        else
                        { //非全部移动
                            wh.STATUS = "1";
                            so.STATUS = "1";
                            //hwy.ADDRESS = wh.ADDRESS;
                            smy.NUM = smy.NUM - num;
                            sm.NUM = sm.NUM + num;
                            //smy.DEPOTWBS = wh.ID.ToString();
                        }
                    }
                    else
                    { //不可以移动
                        throw new Exception("不是同一种货物,不可以移动");
                    }
                }
            }
        }


        /// <summary>
        /// 单个入库
        /// </summary>
        /// <returns></returns>
        //[ActionCommand(name = "入库", title = "入库", index = 10, icon = "icon-ok", isalert = true)]
        public new string OnePutin()
        {
            string returnStr = CheckPutInData(controller);
            if (returnStr != "Y")
                return returnStr;
            if (controller == "0")
                controller = "入库";
            if (controller == "1")
                controller = "出库";
            StockInfoMaterials stockinfo = new StockInfoMaterials();
            stockinfo.Code = SmCode;
            //stockinfo.BATCHNO = SmBatchno;
            //stockinfo.SENBATCHNO = SmSenbatchno;
            stockinfo.DEPOTWBS = SmDepotwbs.ToString();
            stockinfo.PORTCODE = SmPortcode;
            stockinfo.NUM = Convert.ToDouble(SmNum);
            EntityList<Materials> list1 = new EntityList<Materials>(this.model.GetDataAction());
            list1.GetData(" ID='" + SmCode + "'");
            putin(stockinfo, controller, this.model.GetDataAction());
            //同步
            synchronization();
            SmCode = "";
            SmDepotwbs = "";
            SmPortcode = "";
            SmBatchno = "";
            SmSenbatchno = "";
            SmNum = "";
            controller = "";
            return "Y";
        }

        public void synchronization()
        {
            try
            {
                EntityList<Materials> list1 = new EntityList<Materials>(this.model.GetDataAction());
                list1.GetData(" ID=" + SmCode);
                Materials ms = list1[0];
                DateTime dt = DateTime.Now;
                int dtYear = dt.Year;
                int dtMonth = dt.Month;
                int dtDay = dt.Day;
                string Rq = dtYear + "," + dtMonth + "," + dtDay;
                string Xh;
                string Bm;
                string Dwh;
                string Dwmc;
                string Pm;
                string Gg;
                string Rksl;
                string Rkdh;
                //入库
                if (controller == "入库")
                {
                    EntityList<StockInOrder> list2 = new EntityList<StockInOrder>(this.model.GetDataAction());
                    list2.GetData(" ID=" + OrderId);
                    StockInOrder sio = list2[0];
                    BusinessCustomer bc = new BusinessCustomer();
                    EntityList<BusinessCustomer> list3 = new EntityList<BusinessCustomer>(this.model.GetDataAction());
                    if (sio.CLIENTNO != "")
                        list3.GetData(" ID=" + sio.CLIENTNO);
                    if (list3.Count > 0)
                    {
                        bc = list3[0];
                    }
                    string strCon1 = ConfigurationManager.AppSettings["FOXIPKC"].ToString() + "IPSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    DataTable dt1 = BusFoxProHelper.ExecuteDataTable(strCon1, CommandType.Text, "SELECT MAX(Xh) as Xh from Ipsjk");
                    Xh = dt1.Rows[0]["Xh"].ToString();
                    Bm = ms.Code;
                    Gg = ms.FNAME;
                    Dwh = bc.Code;
                    Dwmc = bc.CUSTOMERNAME;
                    Pm = "鸭产品";
                    Rksl = SmNum;
                    Rkdh = sio.Code;
                    string strSql = "";
                    string strOldSql = "SELECT * from ipsjk where Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Rksl>0";
                    DataTable dtOldIpkc = BusFoxProHelper.ExecuteDataTable(strCon1, CommandType.Text, strOldSql);
                    decimal oldNum = 0;
                    if (dtOldIpkc.Rows.Count > 0)
                    {
                        //更新仓库
                        oldNum = Convert.ToDecimal(dtOldIpkc.Rows[0]["Rksl"].ToString());
                        oldNum = oldNum + Convert.ToDecimal(Rksl);
                        strSql = "UPDATE ipsjk set Rksl=" + oldNum + " where  Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Rksl>0";
                    }
                    else
                    {
                        //插入仓库
                        strSql = "insert into Ipsjk(Xh,Rq,Bm,Dwh,Dwmc,Pm,Gg,Rksl,Iksl,Jcsl,Dj,Rkje,Ikje,Jcje,Mbvl,Zy,Rkdh,Ikdh,Cfdd,Pvh,Xuf,Bzvu,Ixb1,Ixb2,Ixb3) values('" + Xh + "',date(" + Rq + "),'" + Bm.Substring(3, 6) + "','" + Dwh + "','" + Dwmc + "','" + Pm + "','" + Gg + "'," + Convert.ToDecimal(Rksl) + ",0,0,0,0,0,0,0,'','" + Rkdh + "','','','','','',0,0,'') ";
                    }
                    string strCon = ConfigurationManager.AppSettings["FOXIPKC"].ToString() + "IPSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    BusFoxProHelper.ExecuteNonQuery(strCon, CommandType.Text, strSql);
                }
                //出库
                else
                {
                    string Ywyh = "";
                    string Ywy = "";
                    string Qyh = "";
                    string Qymc = "";
                    string Fhr = "";
                    string Iksl = "";
                    string Je = "";
                    Xh = "";
                    string Ikdh = "";
                    string Dj = "";
                    EntityList<StockOutOrder> list2 = new EntityList<StockOutOrder>(this.model.GetDataAction());
                    list2.GetData(" ID=" + OrderId);
                    SFStockOutOrder sio = (SFStockOutOrder)list2[0];
                    BusinessCustomer bc = new BusinessCustomer();
                    EntityList<BusinessCustomer> list3 = new EntityList<BusinessCustomer>(this.model.GetDataAction());
                    if (sio.CLIENTNO != "")
                        list3.GetData(" ID=" + sio.CLIENTNO);
                    if (list3.Count > 0)
                    {
                        bc = list3[0];
                    }
                    Bm = ms.Code;
                    Ywyh = user.ID.ToString().PadLeft(3, '0');
                    Ywy = user.name;
                    if (sio.FREGIONID.ToString() != "0")
                    {
                        EntityList<Region> listrn = new EntityList<Region>(this.model.GetDataAction());
                        listrn.GetData(" ID=" + sio.FREGIONID);
                        Qyh = listrn[0].ID.ToString().PadLeft(3, '0');
                        Qymc = listrn[0].RegionName;
                    }
                    Fhr = Rq;
                    Gg = ms.FNAME;
                    Dwh = bc.ID.ToString().PadLeft(4, '0');
                    Dwmc = bc.CUSTOMERNAME;
                    Pm = "鸭产品";
                    Iksl = (Convert.ToDecimal(SmNum) * (-1)).ToString();
                    Ikdh = sio.Code;
                    Je = (ms.PRICE * Convert.ToDouble(SmNum)).ToString();
                    Dj = ms.PRICE.ToString();
                    Xh = Ikdh;
                    string strSql = "";
                    string strCon = "";
                    string strOldSql = "";
                    decimal oldNum = 0;
                    DataTable dtOldIpkc = null;
                    strCon = ConfigurationManager.AppSettings["FOXXG"].ToString() + "XUSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    strOldSql = "SELECT * from Xusjk where Fhr={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "' and Xh='" + Xh + "'";
                    dtOldIpkc = BusFoxProHelper.ExecuteDataTable(strCon, CommandType.Text, strOldSql);
                    oldNum = 0;
                    if (dtOldIpkc.Rows.Count > 0)
                    {
                        oldNum = Convert.ToDecimal(dtOldIpkc.Rows[0]["Sl"].ToString());
                        oldNum = oldNum + Convert.ToDecimal(Iksl);
                        //更新销管
                        strSql = "UPDATE Xusjk set Sl=" + oldNum + " where  Fhr={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "' and Xh='" + Xh + "'";

                    }
                    else
                    {
                        //插入销管
                        strSql = "insert into Xusjk(Xh,Bm,Ywyh,Ywy,Qyh,Qymc,Fhr,Dwh,Dwmc,Pm,Gg,Sl,Dj,Je,Fph,Til,Pvh,Mbvl,Xuti,Xufy,Jsfu,Shr,Hkr,Hkje,Qkje,Hhqk,Nbjg,Djie,Jgie,Bzvu,Jxrq,Xdju,Lxvi,Lxbl,Thyy,Uirq,Qyfz,Ixb1,Ixb2,Ixb3)  ";
                        strSql = strSql + "values('" + Xh + "','" + Bm.Substring(3, 6) + "','" + Ywyh + "','" + Ywy + "','" + Qyh + "','" + Qymc + "',date(" + Fhr + "),'" + Dwh + "','" + Dwmc + "','" + Pm + "','" + Gg + "'," + Iksl + "," + Dj + "," + Je + ",'" + Xh + "',0,'',0,0,0,'','',date(" + Fhr + "),0,0,0,0,0,0,'',date(" + Fhr + "),0,0,0,'',date(" + Fhr + "),'',0,0,'')";
                    }
                    BusFoxProHelper.ExecuteNonQuery(strCon, CommandType.Text, strSql);
                    strCon = ConfigurationManager.AppSettings["FOXIPKC"].ToString() + "IPSJK.DBF" + ConfigurationManager.AppSettings["ENDCONN"].ToString();
                    strOldSql = "SELECT * from IPSJK where Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Iksl>0 and Xh='" + Xh + "'";
                    dtOldIpkc = BusFoxProHelper.ExecuteDataTable(strCon, CommandType.Text, strOldSql);
                    oldNum = 0;
                    if (dtOldIpkc.Rows.Count > 0)
                    {
                        oldNum = Convert.ToDecimal(dtOldIpkc.Rows[0]["Iksl"].ToString());
                        oldNum = oldNum + Convert.ToDecimal(Iksl);
                        //更新仓库
                        strSql = "UPDATE IPSJK set Iksl=" + oldNum + " where  Rq={^" + DateTime.Now.Date + "} and Bm='" + Bm.Substring(3, 6) + "'  and Iksl>0  and Xh='" + Xh + "'";
                    }
                    else
                    {
                        //插入仓库
                        strSql = "insert into Ipsjk(Xh,Rq,Bm,Dwh,Dwmc,Pm,Gg,Rksl,Iksl,Jcsl,Dj,Rkje,Ikje,Jcje,Mbvl,Zy,Rkdh,Ikdh,Cfdd,Pvh,Xuf,Bzvu,Ixb1,Ixb2,Ixb3) values('" + Xh + "',date(" + Rq + "),'" + Bm.Substring(3, 6) + "','" + Dwh + "','" + Dwmc + "','" + Pm + "','" + Gg + "',0," + Convert.ToDecimal(Iksl) + ",0,0,0,0,0,0,'',',','" + Ikdh + "','','','','',0,0,'') ";
                    }
                    BusFoxProHelper.ExecuteNonQuery(strCon, CommandType.Text, strSql);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private string CheckPutInData(string strcontroller)
        {
            EntityList<Ports> list1 = new EntityList<Ports>(this.model.GetDataAction());
            list1.GetData(" ID='" + SmPortcode + "'");
            if (list1.Count == 0)
                return "系统无此托盘！";
            else
            {
                Ports ps = list1[0];
                if (strcontroller == "0")
                {
                    if (ps.STATUS == "1")
                        return "此托盘处于占用状态，不能进行扫描！";
                }
            }
            if (SmCode == null || SmCode == "")
                return "请选择物料！";
            return "Y";
        }

    }
}
